//
//  H5ViewController.m
//  ExampleApp-iOS
//
//  Created by Marcus Westin on 1/13/14.
//  Copyright (c) 2014 Marcus Westin. All rights reserved.
//

#import "H5ViewController.h"
#import "WKWebViewJavascriptBridge.h"
#import "UpdateHeadPhotoViewController.h"
#import "UserRequest.h"
#import "AddCarViewController.h"
#import "LoginViewController.h"
#import "BaseNavigationController.h"
#import "AppDelegate.h"
#import "UserModel.h"

#import "Cycling-Swift.h"
#import <CoreLocation/CoreLocation.h>

#import "RouteRequest.h"
#import "EditRouteController.h"
#import "HealthDataRequest.h"

#import <UserNotifications/UserNotifications.h>
#import <AFNetworking/AFNetworking.h>

static AFNetworkReachabilityManager *manager = nil;

@interface H5ViewController ()<CLLocationManagerDelegate>

@property WKWebViewJavascriptBridge* bridge;
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, retain) CLLocation *myLocation;
@property (nonatomic, strong) WKWebView *webView;

@property (nonatomic) BOOL notificaitonHasOn;
@property (nonatomic, copy) WVJBResponseCallback notificationChangeCallbackBlock;

@end

@implementation H5ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    [self startLocation];
    if (_bridge) { return; }
    WKWebView* webView = [[NSClassFromString(@"WKWebView") alloc] initWithFrame:self.view.bounds];
    [webView setOpaque:NO];
    webView.navigationDelegate = self;
    webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    [self loadExamplePage:webView];

    [self.view addSubview:webView];
    self.webView = webView;
    
    [WKWebViewJavascriptBridge enableLogging];
    _bridge = [WKWebViewJavascriptBridge bridgeForWebView:webView];
    [_bridge setWebViewDelegate:self];

    // js调用oc传token，语言
    [_bridge registerHandler:@"loadUserInfo" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"testObjcCallback called: %@", data);
        NSString *token = [USERDEFAULTS valueForKey:@"Token"];
        NSString *language = [[CycLanguage sharedInstance] currentLanguage];
        responseCallback(@{@"token":token,@"lang":language});
    }];
    
    // js调用oc传状态栏高度
    [_bridge registerHandler:@"getTopHeight" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"testObjcCallback called: %@", data);
        NSString *height = [NSString stringWithFormat:@"%f",SafeAreaTopHeight];
        responseCallback(@{@"height":height});
    }];
    
    [_bridge registerHandler:@"chooseCars" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"testObjcCallback called: %@", data);
        NSLog(@"========= chooseCars");
        //ios参数 {id:'12'}
        if(self.block){
            self.block(data[@"id"]);
        }
    }];
    
    [_bridge registerHandler:@"addcarsphoto" handler:^(id data, WVJBResponseCallback responseCallback) {
        UpdateHeadPhotoViewController *vc = [[UpdateHeadPhotoViewController alloc] init];
        vc.carID = data[@"id"];
        vc.model = self.model;
        vc.changedBlock = ^{
            [self.bridge callHandler:@"goChangeimage"];
        };
        [self.navigationController pushViewController:vc animated:YES];
    }];
    
    [_bridge registerHandler:@"addCarsclick" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"testObjcCallback called: %@", data);
        NSLog(@"========= addCarsclick");
        [self addCar];
    }];
    
    [_bridge registerHandler:@"clearHistory" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"testObjcCallback called: %@", data);
        NSLog(@"========= clearHistory");

    }];
    [_bridge registerHandler:@"onBackPress" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"========= onBackPress");

        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    [_bridge registerHandler:@"startEditHead" handler:^(id data, WVJBResponseCallback responseCallback) {
        UpdateHeadPhotoViewController *vc = [[UpdateHeadPhotoViewController alloc] init];
        vc.model = self.model;
        vc.changedBlock = ^{
            [self.bridge callHandler:@"goChangeimage"];
        };
        [self.navigationController pushViewController:vc animated:YES];
    }];
    
    // 获取h5当前设置语言
    [_bridge registerHandler:@"getLangues" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"========= getLangues%@",data);
        NSString *language = data[@"id"];
        if([language isEqualToString:@"zh"]){
            language = @"zh-Hans";
        }
        [[CycLanguage sharedInstance] setLanguage:language];
        [[NSNotificationCenter defaultCenter] postNotificationName:CycLanguageNotification object:nil];
    }];

    // 打开苹果健康 -- 链接服务
    [_bridge registerHandler:@"getHealthServe" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"========= getHealthServe");

        [self openAppleHealthLink];
    }];
    //  连接设备 -- 健康见解
    [_bridge registerHandler:@"getManagementLink" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"========= getManagementLink");

        [self addCar];
    }];
    
    // 退出登陆 -- 设置
    [_bridge registerHandler:@"loginOut" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"========= loginOut");
        [UserRequest logoutResult:^(BOOL ret) {
            UserModel *user = [UserModel currentUserInfo];
            [[NSUserDefaults standardUserDefaults] setValue:nil forKey:@"Token"];
            [user updateUserInfo];
            [UserModel setLoginSatus:NO];
            appDelegate.window.rootViewController = [[BaseNavigationController alloc] initWithRootViewController:[[LoginViewController alloc] init]];
            [appDelegate.window makeKeyAndVisible];
        }];
    }];
    
    // h5修改信息
    [_bridge registerHandler:@"userInfoEdit" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"========= userInfoEdit %@ == %@",responseCallback,data);
    }];
    
    //进入添加路线页面
    [_bridge registerHandler:@"addRoute" handler:^(id data, WVJBResponseCallback responseCallback) {
        [self editRouteWithRouteID:[[(NSDictionary *)data valueForKey:@"id"] integerValue]];
    }];
    
    //网页加载完成
    [_bridge registerHandler:@"jsonload" handler:^(id data, WVJBResponseCallback responseCallback) {
        [self removeLoadingView];
        
//        [self showHudTipStr:@"h5让我消失的"];
    }];
    
    //开始加载动画
    [_bridge registerHandler:@"showLoading" handler:^(id data, WVJBResponseCallback responseCallback) {
        [self showLoadingViewWithText:@""];
    }];
    //移除加载动画
    [_bridge registerHandler:@"hideLoading" handler:^(id data, WVJBResponseCallback responseCallback) {
        [self removeLoadingView];
    }];
    
    //通知权限
    [_bridge registerHandler:@"getNoticeStatus" handler:^(id data, WVJBResponseCallback responseCallback) {
        [self requestNotificationPermissionComplete:^(NSInteger status) {
            responseCallback(@{@"isopen" : @(status)});
        }];
    }];
    [_bridge registerHandler:@"changeNotice" handler:^(id data, WVJBResponseCallback responseCallback) {
        if (@available(iOS 15.4, *)) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenNotificationSettingsURLString] options:@{} completionHandler:^(BOOL success) {
                
            }];
        } else {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:^(BOOL success) {
                
            }];
        }
        self.notificationChangeCallbackBlock = responseCallback;
    }];
    if([self.url isEqualToString:Cyc_WEBURL_SETTINGS]) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterForegroundNotification:) name:UIApplicationWillEnterForegroundNotification object:nil];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

// 添加车辆
- (void)addCar {
    AddCarViewController  *vc = [AddCarViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}

// 打开苹果健康
- (void)openAppleHealthLink {
    [self requestHealthAppAuthorizationOnComplete:^(BOOL granted, BOOL shouldOpenHealthApp) {
        if(shouldOpenHealthApp) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"x-apple-health://app/"] options:@{} completionHandler:^(BOOL success) {
                
            }];
        } else {
            [HealthDataRequest requestHealthDateRangeWithComplete:nil];
        }
    }];
}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"webViewDidStartLoad");
    
    [self showLoadingViewWithText:nil];
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"webViewDidFinishLoad");
    
    //WKWebview 禁止长按(超链接、图片、文本...)弹出效果
    [webView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none';" completionHandler:nil];
    [webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none';"completionHandler:nil];
    [self removeLoadingView];
    
//    [self showHudTipStr:@"webView加载完成消失Loading动画"];
}

- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
    NSLog(@"错误了:%@", error);
    [self removeLoadingView];
    
//    [self showHudTipStr:@"webView加载失败了才消失Loading动画的"];
}

- (void)loadExamplePage:(WKWebView*)webView {
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]]];
}

//开始定位
- (void)startLocation {
    //初始化定位管理者
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;

    //判断设备是否能够进行定位
    if ([CLLocationManager locationServicesEnabled]) {
        //精确度获取到米
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        //设置过滤器为无
        self.locationManager.distanceFilter = kCLDistanceFilterNone;
        // 取得定位权限，有两个方法，取决于你的定位使用情况
        //一个是requestAlwaysAuthorization，一个是requestWhenInUseAuthorization
        [self.locationManager requestWhenInUseAuthorization];
        //开始获取定位
        [self.locationManager startUpdatingLocation];
        //地理信息
//        self.geoCoder = [[CLGeocoder alloc] init];
    } else {
        DebugLog(@"error");
    }
}

//设置获取位置信息的代理方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    NSLog(@"%lu", (unsigned long)locations.count);
    self.myLocation = locations.lastObject;
    DebugLog(@"经度：%f 纬度：%f", _myLocation.coordinate.longitude, _myLocation.coordinate.latitude);
    
    [self.bridge registerHandler:@"getlocationInfo" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"testObjcCallback called: %@", data);
//        NSString *token = [USERDEFAULTS valueForKey:@"Token"];
//        NSString *language = [[CycLanguage sharedInstance] currentLanguage];
        responseCallback(@{@"lat":[NSString stringWithFormat:@"%f",self.myLocation.coordinate.latitude],@"lng":[NSString stringWithFormat:@"%f",self.myLocation.coordinate.longitude]});
    }];
    
    //不用的时候关闭更新位置服务，不关闭的话这个 delegate 隔一定的时间间隔就会有回调
    [self.locationManager stopUpdatingLocation];
    
}

//编辑路线
- (void)editRouteWithRouteID:(NSInteger)routeId {
    
    [RouteRequest getCyclingRouteDetailWithId:routeId result:^(CyclingRouteDetailModel *model) {
//        self.editModel.detailModel = model;
        EditRouteController *editRouteVC = [[EditRouteController alloc] init];
        NSDictionary *dic = [model mj_keyValues];
        CyclingRouteEditModel *editModel = [CyclingRouteEditModel mj_objectWithKeyValues:dic];
        editModel.detailModel = model;
        editModel.cid = model.routeId;
        
        editRouteVC.editModel = editModel;
        editRouteVC.isAdd = YES;
        [self.navigationController pushViewController:editRouteVC animated:YES];
    }];
    
}

//通知权限
- (void)requestNotificationPermissionComplete:(void(^)(NSInteger status))complete
{
    [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:(UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError *error) {
        self.notificaitonHasOn = granted;
        if(complete) {
            complete(granted ? 1 : 0);
        }
    }];
}

- (void)applicationDidEnterForegroundNotification:(NSNotification *)notification
{
    if([self.url isEqualToString:Cyc_WEBURL_SETTINGS]) {
        if(self.notificationChangeCallbackBlock) {
            [self requestNotificationPermissionComplete:^(NSInteger status) {
                self.notificationChangeCallbackBlock(@{@"isopen" : @(status)});
                self.notificationChangeCallbackBlock = nil;
            }];
        } else {
            [self requestNotificationPermissionComplete:^(NSInteger status) {
                if(self.notificaitonHasOn != (status == 1)) {
                    [self loadExamplePage:self.webView];
                }
            }];
        }
    }
}

+ (void)preloadVuePageOnWindow:(UIWindow *)window
{
    if(manager == nil) {
        manager = [AFNetworkReachabilityManager managerForDomain:BaseUrl];
    }
    if([manager isReachable]) {
        [self preloadVuePageOnWindow:window];
    } else {
        [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            if(manager.isReachable) {
                [self preloadVuePageOnWindowOnce:window];
                [manager stopMonitoring];
            }
        }];
        [manager startMonitoring];
    }
}

+ (void)preloadVuePageOnWindowOnce:(UIWindow *)window
{
    WKWebView* webView = [[NSClassFromString(@"WKWebView") alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [webView setOpaque:NO];
    webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:Cyc_WEBURL_HELP]]];
    webView.hidden = YES;
    
    [window insertSubview:webView atIndex:0];
}

@end
